package com.zhome.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //允许cookies跨域
        corsConfiguration.setAllowCredentials(true);
        //允许向该服务器提交请求的URI，*表示全部允许，自定义可以添加多个
        corsConfiguration.addAllowedOrigin("*");
        //允许访问的头信息,*表示全部，可以添加多个
        corsConfiguration.addAllowedHeader("*");
        //允许Http请求的方法，*表示全部允许
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对所有的访问请求采码该配置
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}
